<template>
  <common-list>
    <!-- 头部搜素start -->
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        :model="query"
        ref="queryForm"
        v-show="showSearch"
        :inline="true"
        label-width="65px"
      >
        <el-form-item label="组织名称">
          <common-input
            v-model="query.deptName"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>

    <!-- 按钮组织start -->
    <el-row slot="tools" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="edit(null)"
          v-hasPermi="['system:dept:add']"
          :disabled="loading"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <!--列表 start-->
    <common-table
      slot="content"
      isSetRowKey
      :data="list"
      style="width: 100%"
      row-key="deptId"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="deptName"
        label="组织名称"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="上级组织" show-overflow-tooltip prop="parentDept">
      </el-table-column>
      <el-table-column
        prop="orderNum"
        label="排序"
        width="80"
      ></el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="{ row }">
          <el-tag type="success" v-if="row.status == 0">正常</el-tag>
          <el-tag type="danger" v-else-if="row.status == 1">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="操作"
        align="left"
        :width="configItem.IS_SYNC_USER ? '245' : '130'"
      >
        <template slot-scope="{ row }">
          <!-- <el-button type="text" @click="detail(row)">详情</el-button> -->
          <el-button
            type="text"
            @click="handleShake(row)"
            :disabled="!row.freeze || row.isDisabledForShake"
            v-hasPermi="['system:dept:changeStatus']"
          >
            {{ row.status == 0 ? "停用" : "启用" }}
          </el-button>
          <el-button
            type="text"
            @click="edit(row)"
            v-hasPermi="['system:dept:edit']"
            :disabled="!row.freeze"
            >编辑</el-button
          >
          <el-button
            type="text"
            v-if="row.parentId > 0"
            @click="handleDelete(row)"
            v-hasPermi="['system:dept:remove']"
            :disabled="!row.freeze"
            >删除</el-button
          >
          <el-button
            type="text"
            v-if="configItem.IS_SYNC_USER"
            @click="synchronizeOrg(row)"
            :disabled="!row.freeze"
            >同步组织</el-button
          >
          <el-button
            type="text"
            v-if="configItem.IS_SYNC_USER"
            @click="updateOrg(row)"
            :disabled="!row.freeze"
            >更新组织</el-button
          >
        </template>
      </el-table-column>
    </common-table>

    <!-- 列表 end -->
    <editDialog
      :deptId="editDeptId"
      ref="editDialog"
      :deptselect="addList"
      @refresh="getList"
    />
    <orgDetail
      :deptId="editDeptId"
      ref="orgDetail"
      :deptselect="list"
      @refresh="getList"
    />
  </common-list>
</template>

<script>
import editDialog from "./components/orgAdd";
import orgDetail from "./components/orgDetail";
import {
  dept_list,
  dept_delete,
  updateDeptStatus,
  deleteForCheckForDept,
  synchronizeOrg,
} from "@/api/management/usercenter/user.js";
import BaseList from "@/mixins/BaseList";
import { deepClone } from "@/utils/";
export default {
  components: { editDialog, orgDetail },
  mixins: [BaseList],
  props: {},
  data() {
    return {
      addList: [],
      showSearch: true, // 查询部分显示
      loading: false, // table 加载中
      selectionIds: "", // 列表选中数据id
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      parentDept: "",
      query: {
        pageNum: 1,
        pageSize: 10,
        status: null,
      }, // 查询条件
      list: [],
      editDeptId: 0,
      key: "deptId",
      configItem: sp_config,
    };
  },
  watch: {},
  computed: {},
  methods: {
    /**
     * 获取列表
     */
    getList() {
      this.loading = true;
      let query = { ...this.query };
      dept_list(query)
        .then((res) => {
          if (res && res.code === 200) {
            let list = res.data.reduce((r, c) => {
              let parentDept = "";
              if (c.deptFullName.split(",").length > 1) {
                parentDept = c.deptFullName.split(",")[0];
              }
              r.push({
                ...c,
                isDisabledForShake: false,
                parentDept,
              });
              return r;
            }, []);
            this.list = this.handleTree(list, "deptId");
            // if (this.list[0].children) {
            //   this.list[0].children.map((item) => {
            //     item.children = [];
            //   });
            // }
            this.addList = deepClone(this.list);
          } else {
            this.list = [];
            this.handleListTips(res);
          }
        })
        .finally(() => (this.loading = false));
    },

    /**
     * 查询
     */
    handleQuery() {
      this.query.pageNum = 1;
      this.getList();
    },
    /**
     * 重置查询
     */
    resetQuery() {
      this.query = this.$options.data().query;
    },
    /**
     * 停用/启用
     */
    changeStatus(row) {
      return new Promise((resolve, reject) => {
        let status = row.status == 0 ? 1 : 0;
        const params = {
          deptId: row.deptId,
          status,
          ancestors: row.ancestors,
        };
        if (status === 1 && row.children && row.children.length) {
          this.$confirm(
            "该组织存在下级，会同时停用下级组织，是否停用？",
            "警告",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              updateDeptStatus(params)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage("操作成功");
                    resolve(res);
                    this.getList();
                  } else {
                    this.$GlobalErrorConfirm("操作失败", res.msg).then();
                    reject();
                  }
                })
                .catch(() => reject());
            })
            .catch(() => {
              reject();
            });
        } else {
          updateDeptStatus(params)
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("操作成功");
                resolve(res);
                this.getList();
              } else {
                this.$GlobalErrorConfirm("操作失败", res.msg).then();
                reject();
              }
            })
            .catch(() => reject());
        }
      });
    },
    /**
     * 添加/编辑
     */
    edit(row) {
      if (row && row.status == 0) {
        this.$GlobalErrorConfirm("编辑失败", "启用状态下不允许编辑");
      } else {
        if (row && row.deptId > 0) {
          this.editDeptId = row.deptId;
        }
        this.$refs.editDialog.show(row ? { ...row } : {});
      }
    },

    synchronizeOrg(row) {
      this.$GlobalDeleteConfirm("是否确认同步组织")
        .then(() => {
          synchronizeOrg({ modifyMode: "add", deptId: row.deptId }).then(
            (res) => {
              if (res && res.code === 200) {
                this.getList();
                this.$GlobalSuccessMessage(res.msg);
              } else {
                this.$GlobalErrorConfirm("同步失败", res.msg);
              }
            }
          );
        })
        .catch(() => {});
    },

    updateOrg(row) {
      this.$GlobalDeleteConfirm("是否确认更新组织")
        .then(() => {
          synchronizeOrg({ modifyMode: "update", deptId: row.deptId }).then(
            (res) => {
              if (res && res.code === 200) {
                this.getList();
                this.$GlobalSuccessMessage(res.msg);
              } else {
                this.$GlobalErrorConfirm("更新失败", res.msg);
              }
            }
          );
        })
        .catch(() => {});
    },

    /**
     * 详情
     */
    detail(row) {
      if (row && row.deptId > 0) {
        this.editDeptId = row.deptId;
      }
      this.$refs.orgDetail.show(row ? { ...row } : {});
    },
    /**
     * 删除
     */
    deleteData(row) {
      if (row && row.status == 0) {
        this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
      } else {
        let msg;
        if (row.children && row.children.length > 0)
          msg = "该组织下包含下级组织，是否继续操作？";
        this.$GlobalDeleteConfirm(msg)
          .then(() => {
            dept_delete({ deptId: row.deptId }).then((res) => {
              if (res && res.code === 200) {
                this.getList();
                this.$GlobalSuccessMessage("删除成功");
              } else {
                this.$GlobalErrorConfirm("删除失败", res.msg).then();
              }
            });
          })
          .catch(() => {});
      }
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      console.log("ids====>", ids);
      return new Promise((resolve, reject) => {
        deleteForCheckForDept({ deptId: ids })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
  created() {
    this.getList();
  },
  mounted() {},
};
</script>
<style lang="scss" scoped></style>
